import IconFont from '@/components/IconFont';
import { useAnchor } from '@/pages/OrderModule/common/hooks/useAnchor';
import { Anchor, Button, Collapse, Form, Spin } from 'antd';
import { cloneDeep, merge } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import Anchors from './components/Anchors';
import ControlFieldModal from './components/ControlFieldModal';
import SimpleEditFilter from '@/pages/OrderModule/orderList/components/OrderList/components/RightAction/EditColumns/SimpleEditFilter.jsx';
import Express from './components/Express';
import Goods from './components/Goods';
import Label from './components/Label';
import OrderSn from './components/OrderSn';
import OrderState from './components/OrderState';
import OrderTime from './components/OrderTime';
import OrderType from './components/OrderType';
import Price from './components/Price';
import { useQuiteSearch } from './components/QuicklyQuery';
import Remark from './components/Remark';
import WareHouse from './components/WareHouse';
import Store from './components/store';
import { useURLQuery } from '@/pages/OrderModule/common/hooks/useURLQuery'
import { useLocation, useNavigate } from 'react-router-dom';
import { queryExpressList } from './components/Express/server';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';

import {
  defaultCheckedColumns,
  expressItem,
  fieldMap,
  goodsFilterItem,
  labelItem,
  orderFilterItem,
  orderStateFilterItem,
  orderTimeItem,
  orderTypeFilterItem,
  priceFilterItem,
  remarksItem,
  storeFilterItem,
  wareHouseFilterItem,
} from './constant';
import FilterItem from './filterItem';
import Style from './index.module.less';
import { useMemo } from 'react';
import {useFilterFieldsConfig} from '@/pages/OrderModule/orderList/components/Filter/store.js';

const { Panel } = Collapse;
const { Link } = Anchor;

function getCommonConfig(title) {
  if (fieldMap[title]) {
    return {
      title,
      dataIndex: fieldMap[title],
      field: fieldMap[title],
    };
  }

  return {
    title,
    dataIndex: title,
    field: title,
  };
}

// 定义 filterItems 数组，用于渲染筛选条件
const filterItems = [
  {
    name: 'orderSn',
    title: '订单号',
    field: 'orderSn',
    childrenNode: Object.keys(orderFilterItem).map((key) => getCommonConfig(key)),
    Component: OrderSn,
    icon: <IconFont type={'iconorder-sn'}></IconFont>,
    allowSort: true
  },
  {
    test:'lalal',
    name: 'orderState',
    title: '订单状态',
    field: 'orderState',
    childrenNode: Object.keys(orderStateFilterItem).map((key) => getCommonConfig(key)),
    Component: OrderState,
    icon: <IconFont type={'iconorder-state'}></IconFont>,
  },
  {
    name: 'store',
    title: '店铺',
    field: 'store',
    childrenNode: Object.keys(storeFilterItem).map((key) => getCommonConfig(key)),
    Component: Store,
    icon: <IconFont type={'iconstore'}></IconFont>,
  },
  {
    name: 'wareHouse',
    title: '发货仓',
    field: 'wareHouse',
    childrenNode: Object.keys(wareHouseFilterItem).map((key) => getCommonConfig(key)),
    Component: WareHouse,
    icon: <IconFont type={'iconwarehouse'}></IconFont>,
  },
  {
    name: 'goods',
    title: '商品',
    field: 'goods',
    childrenNode: Object.keys(goodsFilterItem).map((key) => getCommonConfig(key)),
    Component: Goods,
    icon: <IconFont type={'iconshopping'}></IconFont>,
  },
  {
    name: 'orderType',
    title: '订单类型',
    field: 'orderType',
    childrenNode: Object.keys(orderTypeFilterItem).map((key) => getCommonConfig(key)),
    Component: OrderType, // 组件
  },
  {
    name: 'price', // 价格
    title: '金额/单价/重量',
    field: 'price',
    childrenNode: Object.keys(priceFilterItem).map((key) => getCommonConfig(key)),
    Component: Price, // 组件
  },
  {
    name: 'express',
    title: '快递公司',
    field: 'express',
    childrenNode: Object.keys(expressItem).map((key) => getCommonConfig(key)),
    Component: Express, // 组件
    icon: <IconFont type={'iconexpress-company'}></IconFont>,
  },
  {
    name: 'label',
    title: '标签/旗帜',
    field: 'label',
    childrenNode: Object.keys(labelItem).map((key) => getCommonConfig(key)),
    Component: Label, // 组件
  },
  {
    name: 'remark',
    title: '留言备注',
    field: 'remark',
    childrenNode: Object.keys(remarksItem).map((key) => getCommonConfig(key)),
    Component: Remark,
  },
  {
    name: 'orderTime',
    title: '订单时间',
    field: 'orderTime',
    childrenNode: Object.keys(orderTimeItem).map((key) => getCommonConfig(key)),
    Component: OrderTime,
    icon: <IconFont type={'iconorder-time'}></IconFont>,
  },
];

const filterForm = {
  orderSn: {
    snArr: undefined, // 系统订单号
    outOrderSnArr: undefined, // 店铺订单号
    qmErpSnArr: undefined, // 奇门erp单号
    tcOrderIdArr: undefined, // 直销单号
    logisticsNoArr: undefined, // 快递单号
    provinceIdArr: [], // 省份ID数组
    // cityIdArr: [], // 城市ID数组
    // districtIdArr: [], // 区域ID数组
    phone: '', // 手机号
    buyerAccount: '', // 买家账号
  },
  orderState: {
    errorIdArr: [],
    stateArr: [], // 订单状态数组
    warehouseOrderStateArr: [], // 仓库状态
    payStateArr: [], // 支付状态数组
  },
  express: {
    logisticsCompanyId: undefined, // 快递公司ID
    logisticsErrorType: undefined, // 物流状态
    callbackFlag: undefined, // 物流回传
  },
  wareHouse: {
    warehouseId: undefined, // 发货仓ID
  },
  label: {
    isFlagOr: true, // 包含旗帜：或者开关
    isLabelOr: true, // 包含标签：或者开关
    containLabelIdArr: [], // 包含标签ID数组
    containFlagArr: [], // 包含旗帜数组
    excludeLabelIdArr: [], // 排除标签ID数组
    excludeFlagArr: [], // 排除旗帜数组
  },
  store: {
    ecStoreIdArr: [], // 平台店铺ID数组
    // qmStoreIdArr: [], // 奇门店铺ID数组
  },
  goods: {
    storeIdArr: [], // 供应商
    goodsSpec: undefined, // 颜色规格
    goodsName: undefined, // 商品名称
    storeCode: undefined, //档口号
    isMatch: undefined, // 匹配状态
    takeState: undefined, // 备货状态
    uniqueCodeArr: undefined, // 商品唯一码数组
    sysSkuCodeArr: [], // 商品编码
    totalGoodsNumMax: undefined, // 货品数量最大值
    totalGoodsNumMin: undefined, // 货品数量最小值
    skuTotalMax: undefined, // 货品种类最大值
    skuTotalMin: undefined, // 货品种类最小值
    isSysComposeGoods: undefined,
    goodsSate: undefined,
    // isSaleCode: undefined, // 是否有快销码
  },
  orderType: {
    isOrderTypeOr: false, // 订单类型：或者开关
    orderTypeMap: {
      merge: false,
      split: false,
      runVolume: false,
      isAutoSource: false,
      isManualSource: false,
      missingSubGoods: false,
      interceptExpressState: false,
      forcedDelivery: false,
      reissue: false,
      barter: false,
    },
  },
  price: {
    storeGoodsPrice: undefined, // 采购价
    isVipGoods: undefined, // 是否会员价
    totalAmountMax: undefined, // 订单金额最大值
    totalAmountMin: undefined, // 订单金额最小值
    goodsAmountMax: undefined, // 商品金额最大值
    goodsAmountMin: undefined, // 商品金额最小值
    packAmountMax: undefined, // 包材费最大值
    packAmountMin: undefined, // 包材费最小值
    payServiceFeeMax: undefined, // 支付服务费最大值
    payServiceFeeMin: undefined, // 支付服务费最小值
    ecShippingAmountMax: undefined, // 平台运费最大值
    ecShippingAmountMin: undefined, // 平台运费最小值
    ecActualPaymentMax: undefined, // 平台实付金额最大值
    ecActualPaymentMin: undefined, // 平台实付金额最小值
    ecReceivableAmountMax: undefined, // 平台应付金额最大值
    ecReceivableAmountMin: undefined, // 平台应付金额最小值
    estimateFreightAmountMax: undefined, // 预估运费金额最大值
    estimateFreightAmountMin: undefined, // 预估运费金额最小值
    weightMax: undefined, // 重量最大值
    weightMin: undefined, // 重量最小值
  },
  remark: {
    hadBuyerMessage: undefined, // 有无买家留言
    buyerMessage: '', // 买家留言
    hadSellerMessage: undefined, // 有无卖家备注
    sellerMessage: '', // 卖家备注
    hadOrderRemark: undefined, // 有无订单备注
    orderRemark: '', // 订单备注
  },
  orderTime: {
    timeType: 'ecPayTime', // 时间类型
    ecPayTimeMax: '', // 平台付款时间最大值
    ecPayTimeMin: '', // 平台付款时间最小值
    checkTimeMax: '', // 订单审核时间最大值
    checkTimeMin: '', // 订单审核时间最小值
    deliveryTimeMax: '', // 订单发货时间最大值
    deliveryTimeMin: '', // 订单发货时间最小值
    ecLastDeliveryTimeMin: undefined, // 剩余发货时间
    ecLastDeliveryTimeMax: undefined, // 剩余发货时间最大值
  },
};

// 定义 Filter 组件
export const Filter = ({ defaultValue, onResize, onChange }) => {
  const [form] = Form.useForm();
  const [filterExpand, setFilterExpand] = useState(true);
  const [anchorVisible, setAnchorVisible] = useState(false);
  const [hightLight, setHightLight] = useState('');
	const [loading, setLoading] = useState(true);
  const resolveFilterForm = merge({}, filterForm, defaultValue);

  const [searchKey, setSearchKey] = useState(0);
  const [clearKey, setClearKey] = useState(0);
  const isInit = useRef(true);

  const location = useLocation()
	const navigate = useNavigate();
  const { query } = useURLQuery()
//   const orderSn = query.orderSn || location.state?.orderSn || ''
//   if (orderSn) {
//     filterForm.orderSn.snArr = orderSn
//   }

  useEffect(() => {
    if(location.pathname == '/views/order/list') {
    const orderSn = query.orderSn || location.state?.orderSn || ''
    if(orderSn) {
        form.setFieldsValue({
            ...filterForm,
            orderSn:{ 
              ...filterForm.orderSn,
              snArr: orderSn,
            }
        })
        handleSearch();
    }else if(isInit.current){
      isInit.current = false;
      handleSearch();
    }
    window.history.replaceState('', '');
    //  navigate('/views/order/list', { replace: true });
    }
  }, [location.pathname])

  const orderSn = query.orderSn || location.state?.orderSn || ''

  if (location.pathname === '/views/order/unpay') {
    filterForm.orderState.payStateArr = [0];
    filterForm.orderState.stateArr = [20]
    filterItems.find((item) => item.name === 'orderState').disabled = ['payStateArr', 'stateArr']
  }else {
    filterForm.orderState.payStateArr = [];
    if(orderSn) {
        filterForm.orderState.stateArr = [];
    } else {
        filterForm.orderState.stateArr = [10];
    }
    filterItems.find((item) => item.name === 'orderState').disabled = false
  }

  // 容器元素
  const container = useRef(null);
  // anchor 元素
  const anchorItems = useRef({});
  const { currentAnchor, scrollToAnchor } = useAnchor(container, anchorItems);

  function scrollToTop() {
    container.current.scrollTo({ top: 0, behavior: 'smooth' });
  }

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  //
  const [editIndex, setEditIndex] = useState(false);

  const stageParams = useRef({});

  const { data: resp, fetch: fetchExpressList } = useFetch(queryExpressList, {}, false);

  useEffect(()=>{
    handleSearch();
    fetchExpressList({ type: 1 });
  }, [])

    // 快递公司列表
    const companyListIds = useMemo(() => {
      if (resp?.data?.length) {
        return resp?.data?.map((item) => item.baseExpressId);
      } 
      return [];
    }, [resp]);

  const handleSearch = (type) => {
    const values = form.getFieldsValue();
    console.log(values,'sdfffffff')
    let query = formatQueryParams(values);
    query.sysSkuCode = query.skuCodeAccurate || query.skuCode
		query.sysSpuCode = query.spuCodeAccurate || query.spuCode
		query.skuSearchFlag = false
		query.spuSearchFlag = false
		if(query.skuCodeAccurate) {
			query.skuSearchFlag = true
		}
		if(query.spuCodeAccurate) {
			query.spuSearchFlag = true
		}
    onChange?.(query);
    setSearchKey(type == 'resetSearch' ? 0 : searchKey + 1);
    type != 'quickSearch' && setClearKey(clearKey + 1);
    // getStaticsNumberFunc();
  }

  const handleReset = () => {
    form.resetFields();
    form.setFieldsValue({
      ...defaultValue,
      // skuCodeAccurate: '',
      // spuCodeAccurate: '',
      // skuCode: '',
      // spuCode: '',
    })
    handleSearch('resetSearch');
  }

  // const getStaticsNumberFunc = async () => {
  //   const { data, success} = await getFieldsOp();
  //   if(success){
     
  //   }
  // }

  const checkFormChange = (value) => {
    // ['express', 'wareHouse', 'store', 'remark', 'orderType', 'price', 'goods', 'label', 'orderSn'].map(item=>{
    //   delete value[item];
    //   delete filterForm[item];
    // })
    let currentValueObj = {}
    Object.keys(value).sort().forEach((key) => {
      currentValueObj[key] = value[key]
    })
    const str = JSON.stringify(currentValueObj);
    let initObj = {}
    const initFilterForm = cloneDeep(filterForm);
    initFilterForm.orderState.stateArr = [];
    Object.keys(initFilterForm).sort().forEach((key) => {
      initObj[key] = initFilterForm[key]
    })
    const str2 = JSON.stringify(initObj);

    if (str !== str2) {
      return true;
    }
    return false;
  }

  const { toggleSearchNode, searchListNode } = useQuiteSearch({ form, clearKey, handleSearch, checkFormChange, allLogisticsCompanyId: companyListIds });

  function handleScroll(e) {
    setAnchorVisible(true);
  }

  function handleResizeExpand(isExpand) {
    setFilterExpand(isExpand);
    setTimeout(() => {
      onResize?.();
    }, 300 /* 动画 */);
  }

  const columns = [];
  const [columnConfigs, setColumnConfigs] = useState(filterItems);

  // 格式化剩余发货时间
  const formatEcLastDeliveryTime = (value) => {
    if (value === "1") {
      // 已超时
      return { max: new Date().getTime()}
    }else if (value === "2") {
      // 12小时内
      return { min: new Date().getTime(), max: new Date().getTime() + 12 * 60 * 60 * 1000}
    }else if (value === "3") {
      // 24小时内
      return { min: new Date().getTime(), max: new Date().getTime() + 24 * 60 * 60 * 1000}
    } else if (value === "4") {
      // 3天内
      return { min: new Date().getTime(), max: new Date().getTime() + 3 * 24 * 60 * 60 * 1000}
    } else {
      return {  }
    }
  }

  const formatQueryParams = (value) => {
    let params = {};
    params = {
      ...value.orderSn,
      ...value.orderState,
      ...value.express,
      ...value.wareHouse,
      ...value.goods,
      ...value.orderType,
      ...value.price,
      ...value.remark,
      ...value.orderTime,
      ...value.store,
      ...value.label,
      isLimit: false
    };
    if (value.orderSn.snArr) {
      params.snArr = value.orderSn?.snArr?.split?.(',');
    }
    if (value.orderSn.logisticsNoArr) {
      params.logisticsNoArr = value.orderSn.logisticsNoArr.split(',');
    }
    if (value.orderSn.outOrderSnArr) {
      params.outOrderSnArr = value.orderSn.outOrderSnArr.split(',');
    }
    if (value.orderSn.qmErpSnArr) {
      params.qmErpSnArr = value.orderSn.qmErpSnArr.split(',');
    }
    if (value.orderSn.qmErpSnArr) {
      params.qmErpSnArr = value.orderSn.qmErpSnArr.split(',');
    }
    if (value.orderSn.tcOrderIdArr) {
      params.tcOrderIdArr = value.orderSn.tcOrderIdArr.split(',');
    }
    if (value.orderSn.sourceOrderNoArr) {
      params.sourceOrderNoArr = value.orderSn.sourceOrderNoArr.split(',');
    }
    if(value.orderSn.provinceIdArr?.length){
      const arr1 = [], arr2 = [], arr3 = [];
      value.orderSn.provinceIdArr.map(leval1=>{
        arr1.push(leval1.id);
        leval1.childs?.map(leval2=>{
          arr2.push(leval2.id);
          leval2.childs?.map(leval3=>{
            arr3.push(leval3.id);
          })
        })
      })
      params.provinceIdArr = arr1;
      params.cityIdArr = arr2;
      params.districtIdArr = arr3;
    }else{
      params.provinceIdArr = [];
      params.cityIdArr = [];
      params.districtIdArr = [];
    }
    if(value.express.logisticsCompanyId?.length){
      if(value.express.logisticsCompanyId.includes(-9999)){
        params.allLogisticsCompanyId = companyListIds;
      }
    }
    if (value.goods.uniqueCodeArr) {
      params.uniqueCodeArr = value.goods.uniqueCodeArr.split(',');
    }
    if (value.remark.sellerMessage) {
      params.hadSellerMessage = true
    }
    if (value.remark.buyerMessage) {
      params.hadBuyerMessage = true
    }
    if (value.remark.orderRemark) {
      params.hadOrderRemark = true
    }
    if (value.orderTime.ecLastDeliveryTime) {
      const {min, max} = formatEcLastDeliveryTime(value.orderTime.ecLastDeliveryTime)
      params.ecLastDeliveryTimeMax = max
      params.ecLastDeliveryTimeMin = min
    }
    // 过滤value.orderType.orderTypeMap中为true的项
    params.orderTypeMap = Object.keys(value.orderType.orderTypeMap).filter((key) => value.orderType.orderTypeMap[key]).reduce((obj, key) => {
      obj[key] = true
      return obj
    }, {})
    return params;
  };

  const handleScrollToAnchor = (name) => {
    setHightLight(name);
    scrollToAnchor(name);
  };

  const resetFilterAnchor = () => {
    setAnchorVisible(false)
    setHightLight('')
  }

  const { isInitLoading, initFieldConfig } = useFilterFieldsConfig();

  function hasParentWithWrapFilterBox(event) {
		let element = event.target;
		while (element && element !== document.body) {
			// 检查当前元素的wrap属性
			if (element.dataset.wrap === 'filter-box') {
				return
			}
			// 向上移动到父元素
			element = element.parentElement;
		}
		setAnchorVisible(false)
	}

  useEffect(() => {
   initData();
    // 点击事件监听器绑定到文档
    document.addEventListener('click', hasParentWithWrapFilterBox);

    return () => {
      document.removeEventListener('click', hasParentWithWrapFilterBox);
    }
  }, [])

	//初始化配置
	const initData = async () => {
		await initFieldConfig();
    setLoading(false)
	}

  // useEffect(() => {
  //   if (location.hash === '#/views/order/unpay') {
  //     filterForm.orderState.payStateArr = [0];
  //     filterItems.find((item) => item.name === 'orderState').disabled = ['payStateArr']
  //   }
  // }, []);

  const SimpleEditFilterProps = {
    code: "ColsSettingOrderFilter",
    filterList: columnConfigs,
    handleOk(columns){
      for(let item of columns) {
        if(item.field == 'goods') {
          for(let obj of item.childrenNode) {
            if(obj.field == 'spuCode' && !obj.checked) {
              const values = form.getFieldsValue();
              values.goods.spuCode = ''
              values.goods.spuCodeAccurate = ''
              values.spuSearchFlag = false
              values.sysSpuCode = ''
              values.spuCode = ''
              form.setFieldsValue({
                ...values
              })
              // onChange(values)
            }
            if(obj.field == 'skuCode' && !obj.checked) {
              const values = form.getFieldsValue();
              values.goods.skuCode = ''
              values.goods.skuCodeAccurate = ''
              values.skuSearchFlag = false
              values.sysSkuCode = ''
              values.skuCode = ''
              form.setFieldsValue({
                ...values
              })
              // onChange(values)
            }
          }
        }
      }
      setColumnConfigs([...columns]);
      setEditIndex(false);
      // handleReset()
    },
    handleCancel(){
      setEditIndex(false);
    },
  }

  const handlePressEnter = () => {
    console.log('enter');
    handleSearch()
  }

  return (
    <div className={`${Style.filter} ${filterExpand ? Style.expand : Style.collapse}`}
      data-wrap="filter-box"
    >
      {filterExpand && anchorVisible && <Anchors items={columnConfigs} current={currentAnchor} scrollToTop={scrollToTop} scrollToAnchor={handleScrollToAnchor}></Anchors>}
      {!filterExpand && (
        <div className={Style['filter-expand-btn']} onClick={() => handleResizeExpand(true)}>
          <IconFont type={'iconexpand'}></IconFont>
        </div>
      )}
      <div className={Style['filter-header']}>
        <Button
          htmlType="submit"
          type="primary"
          icon={<IconFont type="iconsousuo" style={{ color: '#fff' }} />}
          onClick={()=>handleSearch()}
        >
          搜索
        </Button>
        <Button icon={<IconFont type="iconformReset" />} onClick={handleReset}>
          重置
        </Button>
        <div className={Style['filter-collapse-btn']} onClick={() => handleResizeExpand(false)}>
          <IconFont type={'iconcollapse'}></IconFont>
        </div>
      </div>
      <div className={Style['filter-content']} ref={container} onScroll={handleScroll}>
        <Spin spinning={isInitLoading}>
          <Form form={form} className={Style['filter-form']} style={{opacity: isInitLoading ? 0 : 1}}  initialValues={filterForm} onClick={resetFilterAnchor}>
            {searchListNode}
            {columnConfigs.map((item, index) => {
              const { Component, props: _props, slot, disabled, ...args } = item;
              // if(item.name =='orderState'){
              //   console.log(item)
              // }
              return (
                <Form.Item key={index} name={item.name} className={` ${item.name === hightLight ? Style['filter-item-active'] : ''}  ${Style['filter-item']}`} >
                  {slot ? slot : <FilterItem ref={(el) => (anchorItems.current[item.name] = el)} Component={Component} childrenNode={item.childrenNode} disabled={disabled} props={_props} searchKey={searchKey} onPressEnter={handlePressEnter} stageParams={stageParams} />}
                </Form.Item>
              );
            })}
          </Form>
        </Spin>
      </div>
      <div className={Style['filter-footer']}>
        <Button style={{ padding: 0,marginRight: 28 }} type="link" onClick={() => setEditIndex(true)}>
          筛选设置
        </Button>
        {toggleSearchNode}
        {/* <SaveQuicklyQueryModal></SaveQuicklyQueryModal> */}
      </div>
      {editIndex && <SimpleEditFilter {...SimpleEditFilterProps} />}
      {/* {editIndex&&<ControlFieldModal
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
          },
        }}
        columnConfigs={filterItems}
        defaultCheckedColumns={defaultCheckedColumns}
        visible={editIndex}
        onVisibleChange={setEditIndex}
        onColumnsConfigChange={(columns) => {
          setColumnConfigs(columns);
        }}
        scroll={{
          y: `calc(100vh - ${236}px)`,
        }}
        columns={columns}
      ></ControlFieldModal>} */}
    </div>
  );
};
export default Filter;
